package com.example.blog_springboot.controller;

import com.example.blog_springboot.config.NullException;
import com.example.blog_springboot.model.Blog;
import com.example.blog_springboot.model.User;
import com.example.blog_springboot.service.BlogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@RestController
@RequestMapping("/blog")
public class BlogController {

    @Autowired
    private BlogService blogService;

    @GetMapping("/selectAll")
    public List<Blog> selectAll(){
        return blogService.selectAll();
    }

    @GetMapping("/selectOne")
    public Blog selectOne(String blogId) throws Exception {
        if(blogId==null||blogId.equals("")){
            throw new Exception();
        }
        return blogService.selectOne(blogId);
    }

    @PostMapping("/add")
    public void add(Blog blog,@SessionAttribute("user")User user) throws Exception {
        if(blog.getTitle()==null||blog.getTitle().equals("")||blog.getContent()==null||blog.getContent().equals("")){
            throw new NullException();
        }
        blogService.add(blog,user);
    }

    @RequestMapping(value = "/delete",method = RequestMethod.DELETE)
    public void delete(String blogId, @SessionAttribute("user")User user) throws Exception {
        if(blogId==null||blogId.equals("")){
            throw new Exception();
        }
        blogService.delete(blogId,user);
    }

    @GetMapping("/count")
    public int count(){
        List<Blog> list = blogService.selectAll();
        return list.size();
    }
}
